<template>
  <div>
    <video
      ref="myVideo"
      controls
      :preload="preload"
      :autoplay="false"
      width="320px"
      height="240px"
      class="video-js vjs-default-skin vjs-big-play-centered"
    >
      <source :src="src" type="video/mp4" v-if="sourcesType === 'mp4'" />
      <source
        :src="src"
        type="application/x-mpegURL"
        v-if="sourcesType === 'm3u8'"
      />
    </video>
  </div>
</template>

<script>
import videojs from "video.js";
import "video.js/dist/video-js.css";
import "videojs-contrib-hls";
export default {
  name: "hls-video",
  props: {
    /**
     * 资源类型 mp4 m3u8
     * 默认播放mp4
     */
    sourcesType: {
      type: String,
      default: "mp4",
    },
    /**
     * video 标签
     */
    src: {
      type: String,
      default: "auto",
    },
    /**
     * preload
     */
    preload: {
      type: String,
      default: "",
    },
    autoplay: {
      type: Boolean,
      default: false,
    },
    width: {
      type: String,
      default: "320px",
    },
    height: {
      type: String,
      default: "240px",
    },
  },
  data() {
    return {
      player: null,
      /**
       * m3ub参数
       */
      m3u8Params: {
        bigPlayButton: true,
        textTrackDisplay: false,
        posterImage: false,
        errorDisplay: false,
        hls: {
          withCredentials: true,
        },
      },
    };
  },
  mounted() {
    this.initVideo();
  },
  methods: {
    initVideo() {
      console.log("this.src", this.src);
      const _this = this;
      const options =
        this.sourcesType === "mp4" ? this.mp4Params : this.m3u8Params;
      //初始化视频方法
      _this.player = videojs(_this.$refs.myVideo, options).ready(function () {
        videojs.log("Your player is ready!");
        _this.$emit("playerReady", _this.$refs.myVideo);
        this.on("loadstart", function (e) {
          _this.$emit("loadstart");
        });
        this.on("durationchange", function () {
          _this.$emit("durationchange");
        });
        this.on("loadedmetadata", function () {
          _this.$emit("loadedmetadata");
        });
        this.on("loadeddata", function () {
          _this.$emit("loadeddata");
        });
        this.on("canplaythrough", function () {
          _this.$emit("canplaythrough");
        });
        this.on("ended", function () {
          _this.$emit("ended");
        });
        this.on("canplay", function (e) {
          _this.$emit("canplay");
        });
        this.on("progress", function (e) {
          _this.$emit("progress");
        });
        this.on("error", function () {
          _this.$emit("error");
        });
      });
    },
  },
  beforeDestroy() {
    videojs(this.$refs.myVideo).dispose();
    this.$emit("playerDestory");
  },
};
</script>

<style>
</style>